<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% String path = request.getContextPath() ;%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %> 
<%@ taglib uri="/WEB-INF/tld/fmt.tld" prefix="fmt" %>
<%@ taglib uri="/WEB-INF/tld/ui.tld" prefix="ui" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<jsp:include page="../../import.jsp" flush="true" />
<style>
</style>
</head>
<body class="iframeBody">
	<div class="Wrapper">
		<div>
			<form id="ligerForm">
				<div class="fieldset1 tabel_col clearFix">
					<div class="caption">
						<span class="title">借阅申请</span>
					</div>
					<div class="fieldBox col_50">
						<div class="label">合同号</div>
						<div class="field">
							${arcBorrowMainVO.contractNo}
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">交接单名称</div>
						<div class="field">
							${arcBorrowMainVO.arcReceiptName}
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">省公司档案袋编号</div>
						<div class="field">${arcBorrowMainVO.portfolioNumberProvince}
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">总部档案袋编号</div>
						<div class="field">${arcBorrowMainVO.portfolioNumber}
						</div>
					</div>
					
					<div class="caption">
						<span class="title">合同资料、承租人资料、担保人资料 ${arcBorrowMainVO.cstNm}  ${arcBorrowMainVO.contractNo}</span>
					</div>
					<div class="fieldBox col_100">
						<div style="width: 98%; margin-left: 1%;">
							<div id="gridContract" class="sq-grid"></div>
						</div>
					</div>
					
					<div class="caption">
						<span class="title">权证资料</span>
					</div>
					<c:forEach items="${paySchNoList}" var="item">
						<div class="fieldBox col_100">
						${item}
							<div style="width: 98%; margin-left: 1%;">
								<div id="gridPay${item}" class="sq-grid"></div>
							</div>
						</div>
					</c:forEach>
					
					
				<div class="caption">
						<span class="title">接收人信息</span>
					</div>
					<div class="fieldBox col_50">
						<div class="label">工号/姓名</div>
						<div class="field">
							<input id="jobNum"  name="jobNum"  type="text"   class="ui-textbox"  ligerui="width: 160"  />
								<a class="sq-button-hasicon" href="javascript:getSysUsr()"><i class="sqBtnIco_4"></i>查找收件人</a>
						</div>
					</div>
					<div class="fieldBox col_50">
					</div>
					
					<div class="fieldBox col_50">
						<div class="label">收件人（工号）</div>
						<div class="field">
							<input id="idCard"  name="arcPostInfoVO.idCard"  type="text"   class="ui-textbox"  ligerui="width: 160"  disabled="disabled"  
							value="${arcPostInfoVO.idCard}"/>
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">收件人（姓名）</div>
						<div class="field">
							<input id="recipient"  name="arcPostInfoVO.recipient"  type="text"   class="ui-textbox"  ligerui="width: 160"   disabled="disabled"  
							value="${arcPostInfoVO.recipient}"/>
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">联系电话</div>
						<div class="field">
							<input id="mobile"  name="arcPostInfoVO.mobile"  type="text"   class="ui-textbox"  ligerui="width: 160" 
								value="${arcPostInfoVO.mobile}"   validate="{mobile:true}"/>
						</div>
					</div>
					
					<div class="fieldBox col_50">
						<div class="label">接收方式</div>
						<div class="field">
							<select id="sendType"  name="arcPostInfoVO.sendType"  ligerui="width: 160">
									<option value="">请选择</option>
									<c:forEach items="${sendTypeList}" var="item">
										<option  value="${item.key}">${item.value}</option>
									</c:forEach>
								</select>
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">借阅类型</div>
						<div class="field">
							<select id="borrowType"  name="arcPostInfoVO.borrowType"  ligerui="width: 160" >
									<option value="">请选择</option>
									<c:forEach items="${borrowTypeList}" var="item">
										<option value="${item.key}">${item.value}</option>
									</c:forEach>
								</select>
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">借阅用途</div>
						<div class="field">
							<!-- <select id="borrowUse"  name="borrowUse"  ligerui="width: 160">
									<option value="">请选择</option>
								</select> -->
								<input id="borrowUse" name="arcPostInfoVO.borrowUse" data-value=" " placeholder="--请选择--" ltype="combobox">
						</div>
					</div>
					<div class="fieldBox col_100">
						<div class="label">借阅备注</div>
						<div class="field">
							 <textarea id="borrowRemark"  name="arcPostInfoVO.borrowRemark" rows="3" class="l-textarea" style="width:100%">${arcPostInfoVO.borrowRemark}</textarea>
						</div>
					</div>
					<div id="emailInfo" style="display: none;">
						<div class="fieldBox col_50">
							<div class="label">快递公司</div>
							<div class="field">
								<select id="sendCompany"  name="arcPostInfoVO.sendCompany"  ligerui="width: 160" >
										<option value="">请选择</option>
										<c:forEach items="${sendCompanyList}" var="item">
											<option value="${item.key}">${item.value}</option>
										</c:forEach>
									</select>
							</div>
						</div>
						<div class="fieldBox col_50">
							<div class="label">快递单号</div>
							<div class="field">
								<input id="sendNum"  name="arcPostInfoVO.sendNum"  type="text"   class="ui-textbox"  ligerui="width: 160" 
									value="${arcPostInfoVO.sendNum}"   />
							</div>
						</div>
						<div class="fieldBox col_100">
							<div class="label">邮寄地址</div>
							<div class="field">
								<textarea id="sendAddr"  name="arcPostInfoVO.sendAddr" rows="3" class="l-textarea" style="width:100%">${arcPostInfoVO.sendAddr}</textarea>
							</div>
						</div>
					</div>
				</div>
				<div class="btnsBox">
						<span id="saveBtn" class="sq-button sq-button-round" onclick="borrowApplyUpdate();">保存</span>
				</div>
				
			</form>
				
			
			
		</div>
	</div>
	<script type="text/javascript">
	     var  contractNo = "${arcBorrowMainVO.contractNo}";//合同号
	     var arcPostInfoId = "${arcPostInfoVO.id}";//邮寄id
	     
		$(function() {
			//初始化form
			$("#ligerForm").ligerForm({
		        validate : true
		    });
			
			//初始化合同明细
			if(contractNo !="") {
				createGrid("gridContract",1);
			}
			
			//初始化权证资料明细
			<c:forEach items="${paySchNoList}" var="item">
				createGrid("gridPay${item}",2,"${item}");//创建ligerGrid
			</c:forEach>

			//初始化邮寄信息
			liger.get("sendType").selectValue("${arcPostInfoVO.sendType}");//接收方式
			liger.get("borrowType").selectValue("${arcPostInfoVO.borrowType}");//借阅类型
			liger.get("sendCompany").selectValue("${arcPostInfoVO.sendCompany}");//快递公司
			
			//初始化借阅用途
			$("#borrowUse").ligerComboBox({
				valueField: 'key',
				textField: 'value',
				width:150
			});
			
			//初始化借阅类型事件
			$("#borrowType").change(function(){
				setBorrowUse();
			});
			
			//触发借阅类型change事件
			$("#borrowType").trigger("change");
			
			$("#sendType").change(function(){
				if(this.value!= "" && this.value == 0) {//邮寄
					$("#emailInfo").show();
				}else {
					$("#emailInfo").hide();
				}
			});
	    });
		
		
		function createGrid(gridId,arcLevel,payListCode){
			
			var _url = '<%=path%>/archive/arcBorrowMain/arcBorrowDetailList.do?arcBorrowMainId=${arcBorrowMainVO.id}&arcLevel='+arcLevel;
			if(payListCode) {
				_url += '&payListCode='+payListCode;
			}
			
			$("#"+gridId).ligerGrid({
				url:_url,
				method:'get',
				columns:[
					{ display: '权证类别', name: 'fileFlagNm',type:'text'},
					{ display: '权证名称', name: 'fileName',type:'text'},
					{display:'资料类型', name: 'dossierTempNm'},
					{display:'扫描件', name: 'arcMgrDetailVO.scanAttcheList', 
						 render: function (rowdata, rowindex, value) {
	                            var h = '<div class="gridNanoItems">';
	                            $(value).each(function(index, el) {
	                                h = h + '<div class="ellipsis"><a class="curPointer" href="javascript:downFile(';
	                                h+="'"+el.filePath+"'";
	                                h+=",'"+el.fileNm+"'";
	                                h+=')">'+el.fileNm+'</a></div>';
	                            });
	                            return h + '</div>';
	                        }
						},
					{display:'归档地点', name: 'arcMgrDetailVO.arcReceiptDetailVO.arcPlaceNm'},
					/* {display:'存档份数',name: 'arcMgrDetailVO.dossierCountT',type:'int'}, */
					{display:'状态',name: 'arcMgrDetailVO.borrowStatusNm'},
					{display:'是否归还', name: 'originalReturn',
						 editor: {
			                    type: 'select',
			                    data: [{"key":"1","value":"归还"},{"key":"2","value":"不归还"}],
			                    valueField: 'key',
			                    textField: 'value'
			                },
			                valueField: 'originalReturn',
			                textField: 'originalReturnNm',
			                render: function (item) {
			                    return item.originalReturnNm;
			                }
					},
					{ display: '计划归还日期', name: 'returnDate', type: 'date',render:renderDate,format: 'yyyy-MM-dd',editor: { type: 'date' } },
					
					
				],onBeforeSubmitEdit: function (e) {
		        
		        },
			    enabledEdit: true,
				usePager: false,//是否有分页便签
				isScroll: true,//是否有滚动条
				root:'rows',
				record:'total',
				hideLoadButton:false,
				width:'100%',
				height:'200',
				heightDiff:-2,
				checkbox:true,//列表是否有选择框
				rownumbers:true,//列表是否有行号
				selectRowButtonOnly:true,//复选框模式时，是否只允许点击复选框才能选择行
	            onAfterShowData: function () {
                    setNanoScroller();//设置附件列表每行高度
                },
                onBeforeEdit: f_onBeforeEdit0,
                isChecked: function () {
                    return true;//已勾选状态
                }
			});
		}
		
		//发起借阅申请修改
		function borrowApplyUpdate(){
			
			//1、必须勾选
			//1.1 合同类明细
			var _arcBorrowDetailList =  liger.get("gridContract").getSelectedRows(); 
			//1.2 支付表类明细
			<c:forEach items="${paySchNoList}" var="item">
					var gridPayArray = liger.get("gridPay${item}").getSelectedRows();
					for(var j=0;j<gridPayArray.length;j++) {
						_arcBorrowDetailList.push(gridPayArray[j]);
					}
			</c:forEach>
					
			if(_arcBorrowDetailList.length == 0) {
				$.ligerDialog.SQalert({content: "请勾选要借阅的资料",SQ_type: "warning",SQ_showButtons: true,});
				return ;
			}
			
			//2、不可勾选借出状态的资料
			//2.1 合同列表
			if(contractNo !="") {
				if(!checkBorrowState("gridContract")) return;
			}
			//2.2 支付表类
			<c:forEach items="${paySchNoList}" var="item">
					if(!checkBorrowState("gridPay${item}")) return;
			</c:forEach>
			
			
			//3、检查是否归还和计划归还日期
			//3.1 合同列表
			if(contractNo !="") {
				if(!checkReturn("gridContract")) return;
			}
			//3.2 支付表类
			<c:forEach items="${paySchNoList}" var="item">
					if(!checkReturn("gridPay${item}")) return;
			</c:forEach>
			
			//4、检查邮寄信息
			var ligerForm = liger.get("ligerForm");
			if (!ligerForm.valid()) {
			    	$.ligerDialog.SQalert({content:LogUtils.LOG_CMM_MUST_FIX_ITEM_INFO, SQ_type: "warning"});
		            return ; 
		     }
			if($.trim($("#idCard").val()) == ""){
					$.ligerDialog.SQalert({content: "输入工号，点击'查找收件人'，查询出收件人（工号）和收件人（姓名）",SQ_type: "warning",SQ_showButtons: true});
					return ;
			} 
		   if($.trim($("#mobile").val()) == ""){
				$.ligerDialog.SQalert({content: "请填写联系电话",SQ_type: "warning",SQ_showButtons: true});
				return ;
			} 
		   if($.trim($("#sendType").val()) == ""){
				$.ligerDialog.SQalert({content: "请选择接收方式",SQ_type: "warning",SQ_showButtons: true});
				return ;
			}
		   if($.trim($("#borrowType").val()) == ""){
				$.ligerDialog.SQalert({content: "请选择借阅类型",SQ_type: "warning",SQ_showButtons: true});
				return ;
			} 
		   if($.trim($("#borrowUse").val()) == ""){
				$.ligerDialog.SQalert({content: "请选择借阅用途",SQ_type: "warning",SQ_showButtons: true});
				return ;
			} 
		   
		   if($.trim($("#sendType").val()) == 0){
			   if($.trim($("#sendCompany").val()) == ""){
					$.ligerDialog.SQalert({content: "请选择快递公司",SQ_type: "warning",SQ_showButtons: true});
					return ;
				} 
			   if($.trim($("#sendNum").val()) == ""){
					$.ligerDialog.SQalert({content: "请输入快递单号",SQ_type: "warning",SQ_showButtons: true});
					return ;
				}
			   if($.trim($("#sendAddr").val()) == ""){
					$.ligerDialog.SQalert({content: "请输入邮寄地址",SQ_type: "warning",SQ_showButtons: true});
					return ;
				}
			}
		   
			//5 、组织数据，提交后台
			var data = ligerForm.getData();
			data["contractNo"] =contractNo;
			
			
			data["_arcBorrowDetailList"] = JSON.stringify(_arcBorrowDetailList);
			data["id"] = '${arcBorrowMainVO.id}';//借阅申请主表id
			/* data["arcReceiptMainId"] = '${arcMgrMainVO.arcReceiptMainId}';//交接单ID
			data["arcReceiptName"] = '${arcMgrMainVO.arcReceiptName}';//交接单名称
			data["versioni"] = '${arcMgrMainVO.versioni}';//交接单版本号
			data["portfolioNumber"] = '${arcMgrMainVO.portfolioNumber}';//总公司档案袋编号
			data["portfolioNumberProvince"] = '${arcMgrMainVO.portfolioNumberProvince}';//省公司档案袋编号 */
			
			console.log(data);
			//return;
			$.ligerDialog.confirm("确认保存吗?", function (flag) {
					if(!flag) return;
					var wait_dialog = null;
					$.ajax({
						type: 'post',
						dataType: 'json',
						data: data,
						url: '<%=path%>/archive/arcBorrowMain/borrowApplyUpdate.do?',
						beforeSend: function(){
							wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING ,SQ_type: "waitting"});
						},success:function(msg){
							wait_dialog.close();
							if(msg.success == 1){
									$.ligerDialog.SQalert({content: msg.info,SQ_type: "success"});//SQ_timeout: 10000
									//alert(msg.info);
									//Remove_navTab();//关闭当前页面
							}else{
								$.ligerDialog.SQalert({content: msg.info,SQ_type: "error"});
							}
						},error:function (XMLHttpRequest, textStatus, errorThrown) { 
							wait_dialog.close();
							$.ligerDialog.SQalert({content: "网络错误，请稍后重试",SQ_type: "error"});
						} 
					});
			});
		}
		 
		function renderDate(rowdata, index, value){
			var dateStr = "";
			if(value != null && value !=""){
				var date = new Date(value);
				dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
			}
			return dateStr;
		}	
		
		
		function setBorrowUse(){
			if($.trim($("#borrowType").val()) == "") {
				liger.get("borrowUse").clear();
				liger.get("borrowUse").setData({});
			}else {
				 $.ajax({
					type: 'post',
					dataType:'json',
					data:{code:$("#borrowType").val()},
					url: '<%=path%>/archive/arcBorrowMain/getBorrowUse.do',
					success:function(msg){
						 if(msg.success == 1){
							 var borrowUse = liger.get("borrowUse");
							 if(msg.data){
								 borrowUse.setData(msg.data);
								 borrowUse.setValue("${arcPostInfoVO.borrowUse}");//设置默认值
							 }else{
								 borrowUse.clear();
								 borrowUse.setData({});//置空下拉框数据
							 }
						 }else{
							 $.ligerDialog.SQalert({content:msg.info, SQ_type: "error"});
						 }
					}
				}); 
			}
		}
		
		function getSysUsr(){
			
			var jobNum = $.trim($("#jobNum").val());
			if( jobNum == ""){
				$.ligerDialog.SQalert({content: "请填写工号",SQ_type: "warning",SQ_showButtons: true,});
				return;
			}
			
			 $.ajax({
				type: 'get',
				dataType:'json',
				url: '<%=path%>/archive/arcBorrowMain/getSysUsr.do?jobNum='+jobNum,
				success:function(msg){
					console.log(msg);
					 if(msg.success == 1){
						 if(msg.data){
							 $("#idCard").val(msg.data.usrNm);
							 $("#recipient").val(msg.data.refRlNm);
							 $("#mobile").val(msg.data.mp);
						 }else{
							 $.ligerDialog.SQalert({content:"没有查询到对应人员", SQ_type: "warning"});
						 }
					 }else{
						 $.ligerDialog.SQalert({content:msg.info, SQ_type: "error"});
					 }
				}
			}); 
		}
		
		  //设置附件列表每行高度
		 function setNanoScroller () {
	         $('.gridNanoItems').each(function(index, el) {
	             if ($(el).height() > 100 ) {
	            	 $(el).wrap('<div class="gridNanoContainer"><div class="nano"><div class="nano-content">');
	                 $(el).parents('.gridNanoContainer').height(100);
	                 $(".nano").nanoScroller({
	                     preventPageScrolling: true
	                 });
	             };
	         });
	     }
		//下载文件
		function downFile(_url,_name){
			if(SQ.regs.img.test(_name)){
				SQ.imgPreview(_url, true);
			}else{
				window.open(_url);
			}
		}
		
		 //表格列待编辑事件
	    function f_onBeforeEdit0(e) { 
	        if (e.column.name == "originalReturn" || e.column.name == "returnDate") {
	        	var gridId = "gridContract";
	        	if(e.record.arcLevel == 2) {
	        		gridId = "gridPay"+e.record.paylistCode;
	        	}
	        	
	        	var manager = $("#"+gridId).ligerGetGridManager();
				if(manager.isSelected(e.rowindex)){
					return true;
				}else{
					alert('请选中该记录后，再编辑!'); 
					return false;
				}
	        }
	        return true;
	    }
	 
	  //检查是否有借出
		function checkBorrowState(gridId){
			var selectedRows = liger.get(gridId).getSelectedRows();
			for (var i=0; i< selectedRows.length; i++){ 
				if(selectedRows[i].borrowStatus==1) {
					$.ligerDialog.SQalert({content: selectedRows[i].fileFlag+"-"+selectedRows[i].fileName+"已借出的资料无法再借阅",SQ_type: "warning"});
					return false;
				}
    		}
			return true;
		}
	  
		//检查是否归还和计划归还日期
		function checkReturn(gridId){
			var selectedRows = liger.get(gridId).getSelectedRows();
			for (var i=0; i< selectedRows.length; i++){ 
				if(!selectedRows[i].originalReturn) {
					$.ligerDialog.SQalert({content: selectedRows[i].fileFlag+"-"+selectedRows[i].fileName+"请选择是否归还",SQ_type: "warning"});
					return false;
				}
				if(selectedRows[i].originalReturn ==1) {
					if(!selectedRows[i].returnDate) {
						$.ligerDialog.SQalert({content: selectedRows[i].fileFlag+"-"+selectedRows[i].fileName+"请选择计划归还日期",SQ_type: "warning"});
						return false;
					}else if(selectedRows[i].returnDate <= DateUtils.formatDate(new Date(), DateUtils.YYYY_MM_DD)) {
						$.ligerDialog.SQalert({content: selectedRows[i].fileFlag+"-"+selectedRows[i].fileName+"计划归还日期必须大于当前日期",SQ_type: "warning"});
						return false;
					}
				}
				
    		}
			return true;
		}
	</script>
</body>
</html>